"""
检测区域设置对话框
专门用于配置主要颜色检测的区域大小和位置
"""

from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QFormLayout, 
                               QLabel, QSpinBox, QComboBox, QDoubleSpinBox,
                               QPushButton, QGroupBox, QCheckBox, QSlider,
                               QTextEdit, QMessageBox, QFrame)
from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QFont
import pyautogui

class DetectionAreaSettingsDialog(QDialog):
    """检测区域设置对话框"""
    
    def __init__(self, trigger_item, parent=None):
        super().__init__(parent)
        self.trigger_item = trigger_item
        self.setWindowTitle(f"检测区域设置 - {trigger_item.name}")
        self.setModal(True)
        self.resize(600, 500)
        
        self.setup_ui()
        self.load_settings()
    
    def setup_ui(self):
        """设置UI界面"""
        layout = QVBoxLayout(self)
        
        # 标题
        title_label = QLabel("主要颜色检测区域配置")
        title_font = QFont()
        title_font.setPointSize(14)
        title_font.setBold(True)
        title_label.setFont(title_font)
        title_label.setAlignment(Qt.AlignCenter)
        layout.addWidget(title_label)
        
        # 分隔线
        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)
        layout.addWidget(line)
        
        # 屏幕信息
        screen_width, screen_height = pyautogui.size()
        screen_center_x, screen_center_y = screen_width // 2, screen_height // 2
        
        info_label = QLabel(f"屏幕尺寸: {screen_width} x {screen_height} 像素  |  屏幕中心: ({screen_center_x}, {screen_center_y})")
        info_label.setStyleSheet("color: gray; font-size: 11px; padding: 5px;")
        info_label.setAlignment(Qt.AlignCenter)
        layout.addWidget(info_label)
        
        # 检测方法选择
        method_group = QGroupBox("检测方法")
        method_layout = QFormLayout(method_group)
        
        self.detection_method_combo = QComboBox()
        self.detection_method_combo.addItems([
            "dominant_kmeans", "traditional", "kmeans", "hybrid"
        ])
        self.detection_method_combo.setCurrentText(getattr(self.trigger_item, 'detection_method', 'dominant_kmeans'))
        self.detection_method_combo.currentTextChanged.connect(self.on_method_changed)
        method_layout.addRow("检测方法:", self.detection_method_combo)
        
        # 方法说明
        self.method_description = QLabel()
        self.method_description.setWordWrap(True)
        self.method_description.setStyleSheet("color: blue; font-size: 10px; padding: 5px;")
        method_layout.addRow("说明:", self.method_description)
        
        layout.addWidget(method_group)
        
        # 主要颜色检测区域设置
        self.region_group = QGroupBox("主要颜色检测区域")
        region_layout = QFormLayout(self.region_group)
        
        # 区域大小
        self.region_size_spin = QSpinBox()
        self.region_size_spin.setRange(50, 500)
        self.region_size_spin.setSingleStep(10)
        self.region_size_spin.setValue(getattr(self.trigger_item, 'dominant_region_size', 200))
        self.region_size_spin.valueChanged.connect(self.update_region_info)
        region_layout.addRow("区域大小 (像素):", self.region_size_spin)
        
        # 快速设置按钮
        size_buttons_layout = QHBoxLayout()
        for size in [100, 150, 200, 250, 300]:
            btn = QPushButton(f"{size}")
            btn.setFixedWidth(50)
            btn.clicked.connect(lambda checked, s=size: self.region_size_spin.setValue(s))
            size_buttons_layout.addWidget(btn)
        region_layout.addRow("快速设置:", size_buttons_layout)
        
        # 中心偏移
        self.offset_x_spin = QSpinBox()
        self.offset_x_spin.setRange(-500, 500)
        self.offset_x_spin.setValue(getattr(self.trigger_item, 'dominant_center_offset_x', 0))
        self.offset_x_spin.valueChanged.connect(self.update_region_info)
        region_layout.addRow("X偏移 (像素):", self.offset_x_spin)
        
        self.offset_y_spin = QSpinBox()
        self.offset_y_spin.setRange(-500, 500)
        self.offset_y_spin.setValue(getattr(self.trigger_item, 'dominant_center_offset_y', 0))
        self.offset_y_spin.valueChanged.connect(self.update_region_info)
        region_layout.addRow("Y偏移 (像素):", self.offset_y_spin)
        
        # 区域信息显示
        self.region_info_label = QLabel()
        self.region_info_label.setStyleSheet("background-color: #f0f0f0; padding: 8px; border: 1px solid #ccc; font-family: monospace;")
        self.region_info_label.setWordWrap(True)
        region_layout.addRow("区域信息:", self.region_info_label)
        
        layout.addWidget(self.region_group)
        
        # K-Means参数设置
        self.kmeans_group = QGroupBox("K-Means参数")
        kmeans_layout = QFormLayout(self.kmeans_group)
        
        self.clusters_spin = QSpinBox()
        self.clusters_spin.setRange(2, 8)
        self.clusters_spin.setValue(getattr(self.trigger_item, 'kmeans_clusters', 3))
        kmeans_layout.addRow("聚类数量:", self.clusters_spin)
        
        self.tolerance_spin = QSpinBox()
        self.tolerance_spin.setRange(5, 100)
        self.tolerance_spin.setValue(self.trigger_item.tolerance)
        kmeans_layout.addRow("颜色容差:", self.tolerance_spin)
        
        layout.addWidget(self.kmeans_group)
        
        # 游戏预设
        preset_group = QGroupBox("游戏场景预设")
        preset_layout = QHBoxLayout(preset_group)
        
        fps_btn = QPushButton("FPS游戏")
        fps_btn.clicked.connect(lambda: self.apply_preset("fps"))
        preset_layout.addWidget(fps_btn)
        
        moba_btn = QPushButton("MOBA游戏")
        moba_btn.clicked.connect(lambda: self.apply_preset("moba"))
        preset_layout.addWidget(moba_btn)
        
        rpg_btn = QPushButton("RPG游戏")
        rpg_btn.clicked.connect(lambda: self.apply_preset("rpg"))
        preset_layout.addWidget(rpg_btn)
        
        layout.addWidget(preset_group)
        
        # 按钮区域
        button_layout = QHBoxLayout()
        
        # 预览按钮
        self.preview_btn = QPushButton("预览检测区域")
        self.preview_btn.clicked.connect(self.preview_detection_area)
        button_layout.addWidget(self.preview_btn)
        
        button_layout.addStretch()
        
        # 确定和取消按钮
        self.ok_btn = QPushButton("确定")
        self.ok_btn.clicked.connect(self.accept)
        button_layout.addWidget(self.ok_btn)
        
        self.cancel_btn = QPushButton("取消")
        self.cancel_btn.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_btn)
        
        layout.addLayout(button_layout)
        
        # 初始化显示
        self.on_method_changed()
        self.update_region_info()
    
    def on_method_changed(self):
        """检测方法改变时的处理"""
        method = self.detection_method_combo.currentText()
        
        descriptions = {
            "dominant_kmeans": "主要颜色K-Means：专门提取屏幕中心区域的主要颜色，最适合游戏应用。抗噪声强，精度高。",
            "traditional": "传统方法：计算检测区域内像素的平均颜色。速度快，适合纯色区域。",
            "kmeans": "K-Means聚类：使用机器学习提取主要颜色。抗噪声强，适合复杂背景。",
            "hybrid": "混合方法：根据区域大小自动选择最适合的检测方法。智能切换。"
        }
        
        self.method_description.setText(descriptions.get(method, ""))
        
        # 根据方法显示/隐藏相关设置
        is_kmeans_method = method in ["kmeans", "hybrid", "dominant_kmeans"]
        self.region_group.setVisible(method == "dominant_kmeans")
        self.kmeans_group.setVisible(is_kmeans_method)
    
    def update_region_info(self):
        """更新区域信息显示"""
        try:
            screen_width, screen_height = pyautogui.size()
            center_x, center_y = screen_width // 2, screen_height // 2
            
            region_size = self.region_size_spin.value()
            offset_x = self.offset_x_spin.value()
            offset_y = self.offset_y_spin.value()
            
            # 计算实际检测中心
            actual_center_x = center_x + offset_x
            actual_center_y = center_y + offset_y
            
            # 计算区域边界
            half_size = region_size // 2
            left = actual_center_x - half_size
            top = actual_center_y - half_size
            right = actual_center_x + half_size
            bottom = actual_center_y + half_size
            
            # 检查边界
            in_bounds = (left >= 0 and top >= 0 and 
                        right <= screen_width and bottom <= screen_height)
            
            pixel_count = region_size * region_size
            
            info_text = f"检测中心: ({actual_center_x}, {actual_center_y})\n"
            info_text += f"区域范围: ({left}, {top}) 到 ({right}, {bottom})\n"
            info_text += f"区域大小: {region_size} x {region_size} 像素\n"
            info_text += f"总像素数: {pixel_count:,} 个\n"
            info_text += f"边界检查: {'✅ 在屏幕内' if in_bounds else '❌ 超出屏幕边界'}"
            
            self.region_info_label.setText(info_text)
            
            # 根据边界检查设置颜色
            if in_bounds:
                self.region_info_label.setStyleSheet("background-color: #e8f5e8; padding: 8px; border: 1px solid #4caf50; font-family: monospace;")
            else:
                self.region_info_label.setStyleSheet("background-color: #ffeaea; padding: 8px; border: 1px solid #f44336; font-family: monospace;")
            
        except Exception as e:
            self.region_info_label.setText(f"计算错误: {e}")
            self.region_info_label.setStyleSheet("background-color: #fff3cd; padding: 8px; border: 1px solid #ffc107; font-family: monospace;")
    
    def apply_preset(self, preset_type):
        """应用预设配置"""
        presets = {
            "fps": {
                "method": "dominant_kmeans",
                "region_size": 200,
                "clusters": 3,
                "tolerance": 40,
                "offset_x": 0,
                "offset_y": 0,
                "description": "FPS游戏：中等区域，平衡精度和性能，适合敌人检测"
            },
            "moba": {
                "method": "dominant_kmeans", 
                "region_size": 120,
                "clusters": 2,
                "tolerance": 25,
                "offset_x": 0,
                "offset_y": 0,
                "description": "MOBA游戏：小区域，精确UI检测，适合技能和血条"
            },
            "rpg": {
                "method": "dominant_kmeans",
                "region_size": 150,
                "clusters": 3,
                "tolerance": 35,
                "offset_x": 0,
                "offset_y": 0,
                "description": "RPG游戏：适中区域，物品和NPC检测"
            }
        }
        
        if preset_type in presets:
            preset = presets[preset_type]
            
            self.detection_method_combo.setCurrentText(preset["method"])
            self.region_size_spin.setValue(preset["region_size"])
            self.clusters_spin.setValue(preset["clusters"])
            self.tolerance_spin.setValue(preset["tolerance"])
            self.offset_x_spin.setValue(preset["offset_x"])
            self.offset_y_spin.setValue(preset["offset_y"])
            
            QMessageBox.information(self, "预设应用", 
                                  f"已应用{preset_type.upper()}游戏预设\n\n{preset['description']}")
    
    def preview_detection_area(self):
        """预览检测区域"""
        try:
            region_size = self.region_size_spin.value()
            offset_x = self.offset_x_spin.value()
            offset_y = self.offset_y_spin.value()
            
            screen_width, screen_height = pyautogui.size()
            center_x, center_y = screen_width // 2, screen_height // 2
            actual_center_x = center_x + offset_x
            actual_center_y = center_y + offset_y
            half_size = region_size // 2
            left = actual_center_x - half_size
            top = actual_center_y - half_size
            
            # 显示预览信息
            QMessageBox.information(self, "预览检测区域", 
                                  f"将在屏幕上显示红色半透明区域\n\n"
                                  f"区域大小: {region_size}x{region_size} 像素\n"
                                  f"检测中心: ({actual_center_x}, {actual_center_y})\n"
                                  f"偏移: ({offset_x}, {offset_y})\n"
                                  f"显示时间: 3秒")
            
            # 简单的预览实现
            import tkinter as tk
            preview_window = tk.Toplevel()
            preview_window.title("检测区域预览")
            preview_window.geometry(f"{region_size}x{region_size}+{left}+{top}")
            preview_window.attributes('-topmost', True)
            preview_window.attributes('-alpha', 0.4)
            preview_window.configure(bg='red')
            
            label = tk.Label(preview_window, text=f"检测区域\n{region_size}x{region_size}", 
                           bg='red', fg='white', font=("Arial", 12, "bold"))
            label.pack(expand=True)
            
            # 3秒后关闭
            preview_window.after(3000, preview_window.destroy)
            
        except Exception as e:
            QMessageBox.warning(self, "预览失败", f"无法显示预览: {e}")
    
    def load_settings(self):
        """加载当前设置"""
        # 设置已在UI创建时加载
        pass
    
    def accept(self):
        """确定按钮处理"""
        try:
            # 保存设置到触发器
            self.trigger_item.detection_method = self.detection_method_combo.currentText()
            self.trigger_item.kmeans_clusters = self.clusters_spin.value()
            self.trigger_item.tolerance = self.tolerance_spin.value()
            
            # 主要颜色检测设置
            self.trigger_item.dominant_region_size = self.region_size_spin.value()
            self.trigger_item.dominant_center_offset_x = self.offset_x_spin.value()
            self.trigger_item.dominant_center_offset_y = self.offset_y_spin.value()
            
            super().accept()
            
        except Exception as e:
            QMessageBox.warning(self, "保存失败", f"保存设置时出错: {e}")
